layui.use(['form', 'xmSelect', 'laytpl', 'steps', 'dropdown', 'util', 'upload','table','admin','formX'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var xmSelect = layui.xmSelect;
    var laytpl = layui.laytpl;
    var steps = layui.steps;
    var table = layui.table;
    var util = layui.util;
    var upload = layui.upload;
    var formX = layui.formX;
    var admin = layui.admin;
    var tableInfos = [];   // 表信息
    var tbSelIns = [];  // 多选下拉实例
    var formData1 = {}, formData2 = {};  // 表单数据
    var isGoLast = false;  // 是否跳转到最后一步
    var projectId;
    $('[lay-filter="generatorTab"]').css('visibility', 'visible');
    /* 获取模板列表 */
    function getTplList() {
        $.get('/template/group/', function (res) {
            if (0 === res.code) {
                var $sel = $('[lay-filter="generatorFrom4"] select[name="templateId"]');
                if (res.data.length === 0) {
                    $sel.html('<option value="">请选择框架模板</option>');
                } else {
                    $sel.html('');
                    res.data.forEach(function (item) {
                        $sel.append('<option value="' + item.id + '">' + item.name + '</option>');
                    });
                    form.render('select', 'generatorFrom4');
                }
            }
        });
    }
    /* 获取数据源列表 */
    function getDatasourceList() {
        $.get('/datasource/',{"pageNum":1,"pageSize":100}, function (res) {
            if (0 === res.code) {
                var $sel = $('[lay-filter="generatorFrom1"] select[name="dscId"]');
                if (res.data.length === 0) {
                    $sel.html('<option value="">请选择框架模板</option>');
                } else {
                    $sel.html('');
                    res.data.forEach(function (item) {
                        $sel.append('<option value="' + item.id + '">' + item.url + '</option>');
                    });
                    form.render('select', 'generatorFrom1');
                }
            }
        });
    }
    getDatasourceList();
    /* ------------------第一步------------------- */
    // 填写数据库信息,获取表数据
    form.on('submit(generatorSubmit1)', function (data) {
        formData1 = data.field;
        if (!isGoLast) {
            var loadIndex = layer.msg('获取数据表信息...', {icon: 16, shade: 0.01, time: false});
            $.ajax({
                url: '/gen/db/tables',
                data: data.field,
                method: 'get',
                dataType: 'json',
                success: function (res) {
                    layer.close(loadIndex);
                    if (res.code === 0) {
                        tableInfos = res.data || [];
                        initStep2();
                        steps.next('generatorTab');
                    } else {
                        layer.msg(res.msg || '无法连接数据库', {icon: 2, anim: 6});
                    }
                },
                error: function (xhr) {
                    layer.close(loadIndex);
                    layer.msg(xhr.status + ': ' + xhr.statusText, {icon: 2, anim: 6});
                }
            });
        } else {
            isGoLast = false;
            formData2 = {};
            steps.go('generatorTab', 2);
        }
        return false;
    });

    // 最后一步
    $('#btnGoLast').click(function () {
        isGoLast = true;
        $('[lay-filter="generatorSubmit1"]').trigger('click');
        getTplList();
    });

    // 初始化第二步
    function initStep2() {
        $('#btnAddModel').parent().prevAll().remove();
        tbSelIns = [];
        formData2 = {};
        addModel(1);
    }

    /* ------------------第二步------------------- */
    // 添加模块
    function addModel(index) {
        if (tableInfos.length <= 0) return;
        laytpl(tplStep2Item.innerHTML).render({
            modelIndex: index
        }, function (html) {
            $('#btnAddModel').parent().before(html);
            var dataList = [];
            for (var i = 0; i < tableInfos.length; i++) {
                dataList.push({
                    name: tableInfos[i].tableName + '（' + tableInfos[i].tableComment + '）',
                    value: tableInfos[i].tableName
                });
            }
            var ins = xmSelect.render({
                el: '#table_' + index,
                height: '300px',
                autoRow: false,
                data: dataList,
                toolbar: {show: true},
                theme: {color: '#5FB878'},
                on: function (data) {
                    var $input = $('input[name="table_prefix_' + index + '"]');
                    var prefix = [];
                    $.each(data.arr, function (index, item) {
                        var pre = item.value.substring(0, item.value.indexOf('_') + 1);
                        (prefix.indexOf(pre) === -1) && prefix.push(pre);
                    });
                    $input.val(prefix.join(','));
                },
                show: function () {
                    $('#table_' + index + '>xm-select').addClass('xm-select-opened');
                },
                hide: function () {
                    $('#table_' + index + '>xm-select').removeClass('xm-select-opened');
                }
            });
            tbSelIns.push(ins);
        });
    }

    // 增加模块按钮点击事件
    $('#btnAddModel').click(function () {
        if (tableInfos.length > 0) {
            var index = $(this).parent().parent().children('.model-item').length + 1;
            addModel(index);
        } else {
            layer.msg('没有数据表', {icon: 2, anim: 6});
        }
    });

    // 删除模块
    $(document).on('click', '[ew-event="closeCard"]', function () {
        var $card = $(this).parent().parent().parent().parent();
        tbSelIns[parseInt($card.data('index')) - 1] = undefined;
        $card.html('');
        $card.hide();
    });

    // 模块配置表单提交,跳到第三步
    form.on('submit(generatorSubmit2)', function (data) {
        formData2 = data.field;
        // 验证
        var lastModelName = undefined;
        for (var f in formData2) {
            if (!formData2.hasOwnProperty(f)) continue;
            if (f.indexOf('model_') === 0) {
                if (formData2[f] === 'common') {
                    layer.msg('模块名不能为common', {icon: 2, anim: 6});
                    return false;
                }
                if (lastModelName === undefined) {
                    lastModelName = formData2[f];
                } else if (lastModelName === formData2[f]) {
                    layer.msg('多个模块名不能相同', {icon: 2, anim: 6});
                    return false;
                }
            }
        }
        var config = $.extend({}, formData2);
        config = $.extend(config, formData1);
        config.models = [];
        for (var i = 0; i < tbSelIns.length; i++) {
            if (tbSelIns[i]) {
                config.models.push({
                    modelName: config['model_' + (i + 1)],
                    tables: tbSelIns[i].getValue('value'),
                    prefix: config['table_prefix_' + (i + 1)].split(',')
                });
            }
        }
        console.log(config);
        var loadIndex = layer.msg('获取表详情信息...', {icon: 16, shade: 0.01, time: false});

        $.ajax({
            url: '/gen/importTables',
            data: JSON.stringify(config),
            method: 'post',
            dataType: 'json',
            contentType: "application/json;charset=utf-8",
            success: function (res) {
                layer.close(loadIndex);
                if (res.code === 0) {
                    //生成projectId
                    projectId = res.data;
                    initStep2();
                    steps.next('generatorTab');
                    initTable(projectId);
                } else {
                    layer.msg(res.msg || '无法连接数据库', {icon: 2, anim: 6});
                }
            },
            error: function (xhr) {
                layer.close(loadIndex);
                layer.msg(xhr.status + ': ' + xhr.statusText, {icon: 2, anim: 6});
            }
        });
        return false;
    });
    /*-------------------第三步--------------------*/
    function initTable(projectId) {
        /* 渲染表格 */
        var insTb = table.render({
            elem: '#tableTable',
            url: '/gen/tables?projectId='+projectId,
            page: true,
            skin: 'line',
            cellMinWidth: 100,
            cols: [
                [
                    {
                        title:'<input type="checkbox" name="layTableCheckbox" lay-skin="primary" lay-filter="layTableAllChoose">',
                        width:60,
                        templet: '<div><input type="checkbox" name="layTableCheckbox" lay-skin="primary"> {{d.LAY_INDEX}}' +
                            '<input type="hidden" name="columns[{{d.LAY_TABLE_INDEX}}].columnId" value="{{d.columnId}}"></div>'
                    },
                    {field: 'tableName', title: '表名称'},
                    {field: 'tableComment', title: '表描述'},
                    {field: 'className', title: '实体类名'},
                    {
                        field: 'createTime', title: '创建时间',width:160, templet: function (d) {
                            return util.toDateString(d.createTime);
                        }, sort: true
                    },
                    {title: '操作', toolbar: '#tableTbBar', align: 'center', minWidth: 240}
                ]
            ]
        });
    }
    /* 表格工具条点击事件 */
    table.on('tool(tableTable)', function (obj) {
        if (obj.event === 'edit') { // 修改
            showTableInfoEdit(obj.data);
        } else if (obj.event === 'del') { // 删除
            doDel(obj);
        } else if (obj.event === 'reset') { // 重置密码
            resetPsw(obj);
        }
    });
    // 获取表信息
    form.on('submit(generatorSubmit3)', function (data) {
        getTplList();
        steps.next('generatorTab');
        return false;
    });

    /* ------------------第四步------------------- */
    // 项目配置表单提交
    form.on('submit(generatorSubmit4)', function (data) {
        if (!data.field.packageName) {

        }
        if (data.field.packageName === 'common') {
            return layer.msg('包名不能为common', {icon: 2, anim: 6});
        }

        var config = $.extend({}, data.field);
        config.projectId = projectId;
        var loadIndex = layer.msg('正在生成中，请稍后...', {icon: 16, shade: 0.01, time: false});
        $.ajax({
            url: '/gen/gen',
            data: JSON.stringify(config),
            method: 'post',
            dataType: 'json',
            contentType: "application/json;charset=utf-8",
            success: function (res) {
                console.log(res);
                debugger;
                layer.close(loadIndex);
                if (0 === res.code) {
                    layer.msg('项目生成完毕，即将开始下载...', {icon: 1});
                    var $iframe = $('#downloadIframe');
                    if ($iframe.length === 0) {
                        $('body').append('<iframe id="downloadIframe" style="display: none;"></iframe>');
                        $iframe = $('#downloadIframe');
                    }
                    $iframe.attr('src', '/gen/download?file='+res.data);
                } else {
                    layer.alert(res.msg || '生成失败，请检查配置~', {title: '生成失败', icon: 2, shade: 0.01});
                }
            },
            error: function (xhr) {
                layer.close(loadIndex);
                layer.msg(xhr.status + ': ' + xhr.statusText, {icon: 2, anim: 6});
            }
        });
        return false;
    });

    // groupId改变事件
    var $groupId = $('input[name="groupId"]');
    $groupId.on('input', function () {
        $('input[name="packageName"]').val($(this).val());
    });

    /*-----------生成表编辑,展示列-----------*/
    function showTableInfoEdit(mData) {
        var layIndex = admin.open({
            title: (mData ? '修改' : '添加') + '生成表信息',
            url: '/page/table/edit',
            area: ['90%', '60%'],
            offset: '10',
            end: function () {
                if (admin.getLayerData(layIndex, 'formOk')) {  // 判断表单操作成功标识
                    insTb.reload();  // 成功刷新表格
                }
            },
            success: function (layero, dIndex) {
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
                formX.val('tableEditForm',mData);
                form.render();
                /* 渲染表格 */
                var insTb1 = table.render({
                    elem: '#tableColumnTable',
                    url: '/table/'+mData.tableId+'/column',
                    page: false,
                    skin: 'line',
                    height : 'full-250',
                    cols: [
                        [
                            {
                                title:'<input type="checkbox" name="layTableCheckbox" lay-skin="primary" lay-filter="layTableAllChoose">',
                                width:60,
                                templet: '<div><input type="checkbox" name="layTableCheckbox" lay-skin="primary"> {{d.LAY_INDEX}}' +
                                    '<input type="hidden" name="columns[{{d.LAY_TABLE_INDEX}}].columnId" value="{{d.columnId}}"></div>'
                            },
                            {field: 'columnName', title: '字段列名'},
                            {field: 'columnComment', title: '字段描述',templet:'#columnCommentTb'},
                            {field: 'columnType', title: 'DB类型', sort: true},
                            {field: 'javaType', title: 'Java类型',templet: '#javaTypeSelect'},
                            {field: 'javaField', title: 'Java属性',templet: '#javaFieldTb'},
                            {field: 'queryType', title: '查询方式',templet: '#queryTypeSelect'},
                            {field: 'showType', title: '显示类型',templet: '#htmlTypeSelect'},
                            {field: 'isInsert', title: '插入', templet: '#functionInsertTb',width:58},
                            {field: 'isEdit', title: '编辑', templet: '#functionEditTb',width:58},
                            {field: 'isList', title: '列表', templet: '#functionListTb',width:58},
                            {field: 'isQuery', title: '查询', templet: '#functionQueryTb',width:58},
                            {field: 'isRequire', title: '必填', templet: '#functionRequireTb',width:58}
                            /*,
                            {
                                field: 'createTime', title: '创建时间', templet: function (d) {
                                    return util.toDateString(d.createTime);
                                }, sort: true
                            }*/
                        ]
                    ]
                });

                // 表单提交事件
                form.on('submit(tableEditSubmit)', function (data) {
                    B.put({
                        url:'/table/',
                        data:$('#tableEditForm').serializeArray(),
                        dataType: 'json',
                        success:function (res) {
                            layer.close(layIndex);
                            if (res.code === 0) {
                                layer.close(dIndex);
                                layer.msg(res.msg, {icon: 1});
                                insTb.reload({page: {curr: 1}});
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }
                    })
                    return false;
                });
            }
        });
    }
});